package com.bartender.consumer.filter;

import com.bartender.consumer.service.ITokenService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class TokenFilter extends OncePerRequestFilter {

    @Autowired
    private ITokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        String token = request.getHeader("Authorization"); // 从请求头获取 token

        if (token != null && !token.isEmpty()) {
            try {
                // 验证 token
                Claims claims = Jwts.parser()
                        .setSigningKey("abcdefghijklmnopqrstuvwxyz") // 使用相同的密钥
                        .parseClaimsJws(token)
                        .getBody();

                // 可以在这里提取 openid 或其他信息
                String openid = claims.getSubject();
                // 将 openid 存储在请求属性中，以便后续使用
                request.setAttribute("openid", openid);
            } catch (Exception e) {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "无效的 token");
                return;
            }
        } else {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "缺少 token");
            return;
        }

        filterChain.doFilter(request, response); // 继续处理请求
    }
} 